package acom.dhy.qigsaw2test.qigsaw

import android.app.Activity
import android.content.Intent
import com.dhy.annotations.Component
import com.dhy.qigsaw.splash.ISplashFragment
import com.dhy.xintent.putSerializableExtra
import com.google.android.play.core.splitinstall.SplitInstallManager
import com.google.android.play.core.splitinstall.SplitInstallRequest
import org.json.JSONObject
import java.io.File
import java.util.*

private const val SPLASH_FRAGMENT_UPGRADED = "com.iqiyi.qigsaw.sample.java.SplashFragmentUpgraded"

fun loadSplashFragmentUpgraded(loader: ClassLoader): ISplashFragment? {
    return try {
        val splashFragment = Class.forName(SPLASH_FRAGMENT_UPGRADED, false, loader)
        splashFragment.constructors.first().newInstance() as? ISplashFragment
    } catch (e: ClassNotFoundException) {
        null
    }
}

inline fun <reified S> loadAutoService(): S? {
    return try {
        ServiceLoader.load(S::class.java).firstOrNull()
    } catch (e: ServiceConfigurationError) {
        e.printStackTrace()
        null
    }
}

fun Activity.startActivityComponent(@Component className: String, vararg serializable: Any?) {
    val intent = Intent().setClassName(packageName, className)
    if (serializable.isNotEmpty()) intent.putSerializableExtra(*serializable)
    startActivity(intent)
}

fun SplitInstallRequest.Builder.addModules(moduleNames: Collection<String>): SplitInstallRequest.Builder {
    moduleNames.forEach { addModule(it) }
    return this
}

fun SplitInstallManager.isAllInstalled(): Boolean {
    return installedModules == QigsawConfig.DYNAMIC_FEATURES.toSet()
}

/**
 * 插件是否兼容当前 BaseApp
 * */
fun File.isCompatSplitInfo(): Boolean {
    return try {
        val json = JSONObject(readText())
        val qigsawId = json.optString("qigsawId")
        qigsawId == QigsawConfig.QIGSAW_ID
    } catch (e: Exception) {
        e.printStackTrace()
        false
    }
}

fun String.splitInfoMd5(): String {
    // "http://www.qigsaw.com/acom.dhy.qigsaw2test-split-t0-v1.0-c1-330693fb43fa098b28728fdc45315a20.apk"
    return substring(lastIndexOf('-') + 1, lastIndexOf('.'))
}